package cn.tedu.v1_2;

import java.io.*;
import java.net.ConnectException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {

    private Socket socket;
    public Client() {
        try {
            socket=new Socket("127.0.0.1",4545);
        }catch (NullPointerException e){
            System.out.println("友情提示：IP传入错误导致链接失败");
        } catch (UnknownHostException e){
            System.out.println("友情提示：IP传入错误");
        } catch (ConnectException e){
            System.out.println("客户端链接服务器端失败，提示：检查IP/端口");
        } catch (IOException e) {
            System.out.println("客户端链接服务器端失败，提示：检查IP/端口");
        }
    }

    public void start()  {
        //置空流---PrintWriter
        PrintWriter pw=null;
        try {
            //IO流：写出功能
            OutputStream os=socket.getOutputStream();
            InputStream is= socket.getInputStream();
            OutputStreamWriter osw=new OutputStreamWriter(os,"UTF8");
            InputStreamReader isr=new InputStreamReader(is);
            BufferedWriter bw=new BufferedWriter(osw);
            pw=new PrintWriter(bw,true);
            System.out.println("对服务器端说话：");
            Scanner input=new Scanner(System.in);//卡住，等待用户输入
            String line=null;
            while (true){
                line=input.nextLine();
                pw.println(line);
                System.out.println("恭喜你抽中五百万！" );
            }
        }catch (UnsupportedEncodingException e){
            System.out.println("客户端/服务器端编码集有问题！");
        } //catch (ConnectException e){
            //System.out.println("客户端链接服务器端失败，提示：检查IP/端口");
        //}
        catch (IOException e) {
            System.out.println("客户端链接服务器端：IO流操作出现错误");
        } finally {
            if (pw!=null)
                pw.close();
        }
    }

    public static void main(String[] args) {
       Client client=new Client();
        client.start();
    }
}
